package com.lovebridge.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 */
public class AuthorizationFilter  implements Filter {
    private String loginPage;
    private String[] excludePages;

    public void init(FilterConfig filterConfig) throws ServletException {
           loginPage=filterConfig.getInitParameter("loginPage");
           excludePages =filterConfig.getInitParameter("excludePages").split(",");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (isExcludePage(req.getRequestURI()))
        {
            filterChain.doFilter(request, response);
        }
        else
        {
            HttpSession session=req.getSession();
            if (session==null||session.getAttribute("user")==null) {
                req.getRequestDispatcher(loginPage).forward(request, response);
            } else {
               filterChain.doFilter(request, response); 
            }
        }
    }

    private boolean isExcludePage(String requestUrl)
    {
        for(String excludePage: excludePages)
        {
             if (requestUrl.startsWith(excludePage)) {
                 return true;
             }
        }
        return false;
    }

    public void destroy() {
    }
}
